package com.igroupes.ovineherd.service.impl;

import com.igroupes.ovineherd.dto.response.FileUploadResponse;
import com.igroupes.ovineherd.enums.ErrorCode;
import com.igroupes.ovineherd.exception.OvineHerdException;
import com.igroupes.ovineherd.file.core.FileStore;
import com.igroupes.ovineherd.service.FileService;
import com.igroupes.ovineherd.util.StreamUtils;
import com.igroupes.ovineherd.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private FileStore fileStore;

    @Override
    public ResultVO upload(InputStream inputStream, HttpServletRequest request) {
        try {
            inputStream = StreamUtils.supportMarkInputStream(inputStream);
            String fileKey = fileStore.uploadFile(inputStream);
            FileUploadResponse fileUploadResponse = new FileUploadResponse();
            fileUploadResponse.setValue(fileStore.downloadUrl(fileKey));
            ResultVO ret = ResultVO.success(fileUploadResponse);
            return ret;
        } catch (Exception ex) {
            log.error("exception:", ex);
            throw new OvineHerdException(ErrorCode.FILE_UPLOAD_FAIL);
        }

    }

    @Override
    public void download(String key, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            InputStream inputStream = fileStore.fileStream(key);
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[10 * 1024];
            while (inputStream.read(buffer) != -1) {
                out.write(buffer);
            }
        } catch (Exception ex) {
            log.error("exception:", ex);
            throw new OvineHerdException(ErrorCode.FILE_DOWNLOAD_FAIL);
        }
    }


}
